<template>
  <div class="smart-list-navigation">
    <!-- 搜索框 -->
    <div class="search-section">
      <v-text-field
        v-model="searchQuery"
        prepend-inner-icon="mdi-magnify"
        placeholder="搜索"
        variant="outlined"
        density="compact"
        hide-details
        class="mb-4"
      />
    </div>

    <!-- 系统清单 -->
    <div class="system-lists">
      <v-list density="compact" nav>
        <v-list-item
          v-for="list in systemLists"
          :key="list.id"
          :value="list.id"
          :active="currentListId === list.id"
          @click="setCurrentList(list.id)"
          class="list-item"
        >
          <template #prepend>
            <v-icon :icon="list.icon" :color="list.color" size="small" />
          </template>
          
          <v-list-item-title class="list-title">
            {{ list.name }}
          </v-list-item-title>
          
          <template #append>
            <v-chip
              v-if="getListTaskCount(list.id).value > 0"
              :color="list.color"
              size="x-small"
              variant="flat"
            >
              {{ getListTaskCount(list.id).value }}
            </v-chip>
          </template>
        </v-list-item>
      </v-list>
    </div>

    <!-- 自定义清单 -->
    <div v-if="customLists.length > 0" class="custom-lists mt-4">
      <div class="section-header">
        <span class="section-title">自定义清单</span>
        <v-btn
          icon="mdi-plus"
          size="x-small"
          variant="text"
          @click="showAddListDialog = true"
        />
      </div>
      
      <v-list density="compact" nav>
        <v-list-item
          v-for="list in customLists"
          :key="list.id"
          :value="list.id"
          :active="currentListId === list.id"
          @click="setCurrentList(list.id)"
          class="list-item"
        >
          <template #prepend>
            <v-icon :icon="list.icon" :color="list.color" size="small" />
          </template>
          
          <v-list-item-title class="list-title">
            {{ list.name }}
          </v-list-item-title>
          
          <template #append>
            <div class="list-actions">
              <v-chip
                v-if="getListTaskCount(list.id).value > 0"
                :color="list.color"
                size="x-small"
                variant="flat"
                class="mr-2"
              >
                {{ getListTaskCount(list.id).value }}
              </v-chip>
              
              <v-menu>
                <template #activator="{ props }">
                  <v-btn
                    icon="mdi-dots-vertical"
                    size="x-small"
                    variant="text"
                    v-bind="props"
                    @click.stop
                  />
                </template>
                
                <v-list density="compact">
                  <v-list-item @click="editList(list)">
                    <template #prepend>
                      <v-icon icon="mdi-pencil" size="small" />
                    </template>
                    <v-list-item-title>编辑</v-list-item-title>
                  </v-list-item>
                  
                  <v-list-item @click="deleteList(list.id)">
                    <template #prepend>
                      <v-icon icon="mdi-delete" size="small" color="error" />
                    </template>
                    <v-list-item-title class="text-error">删除</v-list-item-title>
                  </v-list-item>
                </v-list>
              </v-menu>
            </div>
          </template>
        </v-list-item>
      </v-list>
    </div>

    <!-- 创建清单按钮 -->
    <div v-else class="create-list-section mt-4">
      <v-btn
        prepend-icon="mdi-plus"
        variant="text"
        color="primary"
        @click="showAddListDialog = true"
        block
      >
        创建清单
      </v-btn>
    </div>

    <!-- 清单编辑对话框 -->
    <ListEditDialog
      v-model="showListDialog"
      :list="editingList"
      @save="saveList"
    />

    <!-- 删除确认对话框 -->
    <v-dialog v-model="showDeleteDialog" max-width="400px">
      <v-card>
        <v-card-title>确认删除</v-card-title>
        <v-card-text>
          确定要删除这个清单吗？清单中的任务不会被删除。
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn 
            color="grey-darken-1" 
            variant="text" 
            @click="showDeleteDialog = false"
          >
            取消
          </v-btn>
          <v-btn 
            color="error" 
            variant="text" 
            @click="confirmDeleteList"
          >
            删除
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useListStore } from '@/stores/listStore'
import { useTaskStore } from '@/stores/taskStore'
import ListEditDialog from './ListEditDialog.vue'
import type { SystemList, CustomList } from '@/types/list'

interface Props {
  currentListId: string
}

interface Emits {
  (e: 'list-selected', listId: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const listStore = useListStore()
const taskStore = useTaskStore()
const searchQuery = ref('')
const showListDialog = ref(false)
const editingList = ref<CustomList | null>(null)
const showDeleteDialog = ref(false)
const deletingListId = ref('')

const systemLists = computed(() => listStore.systemLists)
const customLists = computed(() => listStore.customLists)
const filteredCustomLists = computed(() => {
  if (!searchQuery.value) return customLists.value
  return customLists.value.filter(list => 
    list.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})



const getTaskCount = (listId: string) => {
  const taskStore = useTaskStore()
  switch (listId) {
    case 'today':
      return taskStore.todayCount.value
    case 'tomorrow':
      return taskStore.tomorrowCount.value
    case 'week':
      return taskStore.weekCount.value
    case 'important':
      return taskStore.importantCount.value
    case 'planned':
      return taskStore.plannedCount.value
    case 'tasks':
      return taskStore.tasksCount.value
    case 'completed':
      return taskStore.completedCount.value
    default:
      return taskStore.getTasksByList(listId).length
  }
}

const getListTaskCount = (listId: string) => {
  return { value: getTaskCount(listId) }
}

const setCurrentList = (listId: string) => {
  emit('list-selected', listId)
}

const addCustomList = () => {
  editingList.value = null
  showListDialog.value = true
}

const editList = (list: CustomList) => {
  editingList.value = list
  showListDialog.value = true
}

const deleteList = (listId: string) => {
  deletingListId.value = listId
  showDeleteDialog.value = true
}

const confirmDeleteList = () => {
  if (deletingListId.value) {
    if (confirm('确定要删除这个清单吗？清单中的任务不会被删除。')) {
      listStore.deleteCustomList(deletingListId.value)
      // 如果删除的是当前选中的清单，切换到默认清单
      if (props.currentListId === deletingListId.value) {
        emit('list-selected', 'today')
      }
    }
  }
  showDeleteDialog.value = false
  deletingListId.value = ''
}

const saveList = (listData: Partial<CustomList>) => {
  if (editingList.value) {
    // 编辑现有清单
    listStore.updateCustomList(editingList.value.id, listData)
  } else {
    // 创建新清单
    const newList = listStore.addCustomList({
      name: listData.name!,
      description: listData.description || '',
      icon: listData.icon || 'mdi-format-list-bulleted',
      color: listData.color || 'blue',
      isDefault: listData.isDefault || false
    })
    // 创建后自动选中新清单
    emit('list-selected', newList.id)
  }
}
</script>

<style scoped>
.smart-list-navigation {
  height: 100%;
  overflow-y: auto;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  margin-bottom: 8px;
}

.section-title {
  font-size: 0.875rem;
  font-weight: 500;
  color: rgb(var(--v-theme-on-surface-variant));
}

.list-item {
  border-radius: 8px;
  margin: 2px 8px;
}

.list-title {
  font-size: 0.875rem;
}

.list-actions {
  display: flex;
  align-items: center;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 8px;
  margin-bottom: 16px;
}

.color-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
}

.create-list-section {
  padding: 0 16px;
}
</style>